import Vue from 'vue';
import VueRouter from 'vue-router';
import Register from '../views/Register.vue';
import Login from '../views/Login.vue';
import Main from '../views/Main.vue';

Vue.use(VueRouter);

const routes = [
  //  vue-router 的路由重定向 表示 用 /的时候 默认访问到 /left 这个Hash地址
  { path: '/', redirect: '/login' },
  { path: '/register', component: Register },
  { path: '/login', component: Login },
  { path: '/main', component: Main },
];

const router = new VueRouter({
  routes,
});

//  全局前置守卫 拦截器
router.beforeEach(function (to, from, next) {
  const rg = /main/;
  if (rg.test(to.path)) {
    // 获取 token
    const token = localStorage.getItem('token');
    //  判断 有没有 token
    if (token !== null) {
      // 如果 token 不等于 空
      next();
    } else {
      next('/login');
    }
  } else {
    next();
  }
});

export default router;

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};
